﻿using System;
using System.Diagnostics;
using System.Net;
using Golos.Helper;

namespace Golos.Http
{
    public abstract class HttpServer
    {
        public int Port { get; private set; }

        public HttpServerBase.State GetState()
        {
            return listener.RunState;
        }

        public HttpServer(int port)
        {
            listener = new HttpServerBase(port);
            listener.IncomingRequest += WebServer_IncomingRequest;
            listener.Start();
            Console.WriteLine("Listener accepting requests: {0}", listener.RunState == HttpServerBase.State.Started);
        }

        private void WebServer_IncomingRequest(object sender, HttpHandler e)
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            try
            {
                LogClass.WriteInfoEntry(string.Format("Input request: {0}", e.RequestContext.Request.Url));
                int statusCode = 0;
                IncomingRequest(e.RequestContext, ref statusCode);
                HttpListenerResponse response = e.RequestContext.Response;
                //response.ContentLength64 = response.OutputStream.Length;
                response.OutputStream.Close();
                response.Close();
                stopwatch.Stop();
                LogClass.WriteInfoEntry(string.Format("Complete request: {0}\t{1}", e.RequestContext.Request.Url, stopwatch.Elapsed));
            }
            catch (Exception exception)
            {
                stopwatch.Stop();
                LogClass.WriteInfoEntry(string.Format("Request was aborted: {0}\t{1}\r\n{2}", e.RequestContext.Request.Url, stopwatch.Elapsed, exception));
            }
            
        }

        protected abstract void IncomingRequest(HttpListenerContext context, ref int StatusCode);

        private readonly HttpServerBase listener = null;
    }
}
